<template>
  <div class="min-h-screen bg-gray-50 dark:bg-dark-950">
    <!-- Header -->
    <div class="bg-white dark:bg-dark-900 shadow-sm border-b border-gray-200 dark:border-dark-700 p-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">数据仪表板</h1>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">系统数据概览与分析</p>
        </div>
        <div class="flex items-center space-x-4">
          <button
            @click="refreshData"
            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新数据
          </button>
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div class="p-6 space-y-6">
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <UserGroupIcon class="h-8 w-8 text-blue-500" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">总用户数</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-gray-100">{{ dashboardData.totalUsers }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <ShoppingBagIcon class="h-8 w-8 text-green-500" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">总订单数</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-gray-100">{{ dashboardData.totalOrders }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <CubeIcon class="h-8 w-8 text-yellow-500" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">库存商品</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-gray-100">{{ dashboardData.totalProducts }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <CurrencyDollarIcon class="h-8 w-8 text-purple-500" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">总销售额</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-gray-100">¥{{ formatCurrency(dashboardData.totalRevenue) }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 销售趋势图 -->
        <ChartComponent
          type="line"
          title="销售趋势"
          subtitle="最近30天销售数据"
          :data="salesTrendData"
          height="350px"
          :colors="['#3B82F6', '#10B981']"
          @refresh="refreshData"
        />

        <!-- 产品分类分布 -->
        <ChartComponent
          type="pie"
          title="产品分类分布"
          subtitle="各分类产品占比"
          :data="categoryDistributionData"
          height="350px"
          @refresh="refreshData"
        />
      </div>

      <!-- 订单状态分析 -->
      <ChartComponent
        type="bar"
        title="订单状态分析"
        subtitle="不同状态订单数量统计"
        :data="orderStatusData"
        height="300px"
        :colors="['#10B981', '#F59E0B', '#EF4444', '#6B7280']"
        @refresh="refreshData"
      />

      <!-- 数据表格 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">最新订单</h3>
        </div>
        
        <VexTable
          :data="recentOrders"
          :columns="orderColumns"
          :loading="loading"
          :show-pagination="false"
          :actions="orderActions"
          @action="handleOrderAction"
          height="400px"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { businessAPI } from '@/api'
import VexTable from '@/components/VexTable.vue'
import ChartComponent from '@/components/ChartComponent.vue'
import {
  ArrowPathIcon,
  UserGroupIcon,
  ShoppingBagIcon,
  CubeIcon,
  CurrencyDollarIcon
} from '@heroicons/vue/24/outline'

// State
const loading = ref(false)
const recentOrders = ref([])

const dashboardData = reactive({
  totalUsers: 0,
  totalOrders: 0,
  totalProducts: 0,
  totalRevenue: 0,
  salesTrend: [],
  categoryDistribution: [],
  orderStatus: []
})

// Table columns
const orderColumns = computed(() => [
  {
    field: 'id',
    title: '订单号',
    width: 120,
    type: 'string'
  },
  {
    field: 'customer_name',
    title: '客户',
    width: 150,
    type: 'string'
  },
  {
    field: 'total_amount',
    title: '金额',
    width: 120,
    type: 'number'
  },
  {
    field: 'status',
    title: '状态',
    width: 100,
    type: 'status',
    options: [
      { value: 'pending', label: '待处理', color: 'yellow' },
      { value: 'confirmed', label: '已确认', color: 'blue' },
      { value: 'shipped', label: '已发货', color: 'green' },
      { value: 'delivered', label: '已送达', color: 'green' },
      { value: 'cancelled', label: '已取消', color: 'red' }
    ]
  },
  {
    field: 'created_at',
    title: '创建时间',
    width: 180,
    type: 'datetime'
  }
])

const orderActions = computed(() => [
  {
    key: 'view',
    label: '查看',
    type: 'primary',
    icon: 'EyeIcon'
  },
  {
    key: 'edit',
    label: '编辑',
    type: 'info',
    icon: 'PencilIcon'
  }
])

// Chart data
const salesTrendData = computed(() => ({
  labels: dashboardData.salesTrend.map((item: any) => item.date),
  series: [
    {
      name: '销售额',
      type: 'line',
      data: dashboardData.salesTrend.map((item: any) => item.amount),
      smooth: true
    },
    {
      name: '订单数',
      type: 'line',
      data: dashboardData.salesTrend.map((item: any) => item.orders),
      smooth: true,
      yAxisIndex: 1
    }
  ]
}))

const categoryDistributionData = computed(() => ({
  series: [{
    name: '产品分类',
    type: 'pie',
    radius: ['40%', '70%'],
    data: dashboardData.categoryDistribution.map((item: any) => ({
      name: item.category,
      value: item.count
    }))
  }]
}))

const orderStatusData = computed(() => ({
  labels: dashboardData.orderStatus.map((item: any) => item.status),
  series: [{
    name: '订单数量',
    type: 'bar',
    data: dashboardData.orderStatus.map((item: any) => item.count)
  }]
}))

// Methods
const refreshData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    dashboardData.totalUsers = 1250
    dashboardData.totalOrders = 3420
    dashboardData.totalProducts = 890
    dashboardData.totalRevenue = 2580000
    
    dashboardData.salesTrend = Array.from({ length: 30 }, (_, i) => ({
      date: `2024-${String(Math.floor(i / 30) + 1).padStart(2, '0')}-${String((i % 30) + 1).padStart(2, '0')}`,
      amount: Math.floor(Math.random() * 50000) + 10000,
      orders: Math.floor(Math.random() * 100) + 20
    }))
    
    dashboardData.categoryDistribution = [
      { category: '电子产品', count: 45 },
      { category: '服装', count: 30 },
      { category: '家居', count: 15 },
      { category: '其他', count: 10 }
    ]
    
    dashboardData.orderStatus = [
      { status: '待处理', count: 120 },
      { status: '已确认', count: 280 },
      { status: '已发货', count: 150 },
      { status: '已送达', count: 200 },
      { status: '已取消', count: 50 }
    ]
    
    recentOrders.value = Array.from({ length: 10 }, (_, i) => ({
      id: `ORD${String(i + 1).padStart(6, '0')}`,
      customer_name: `客户${i + 1}`,
      total_amount: Math.floor(Math.random() * 5000) + 100,
      status: ['pending', 'confirmed', 'shipped', 'delivered'][Math.floor(Math.random() * 4)],
      created_at: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    }))
    
  } catch (error) {
    console.error('刷新数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleOrderAction = (action: any, row: any) => {
  console.log('订单操作:', action.key, row)
}

const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('zh-CN').format(amount)
}

// Lifecycle
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
/* 自定义样式 */
</style>
